import {Button, Form, Input, InputNumber, message, Modal, Upload, UploadFile, UploadProps} from "antd";
import React, {useEffect, useState} from "react";
import TextArea from "antd/es/input/TextArea";
import {UploadOutlined, PlusOutlined} from '@ant-design/icons';
import {RcFile} from "antd/es/upload";
import {beforeUpload, getBase64} from "../../../../util";
import {useLocation, useNavigate, useParams} from "react-router-dom";
import {createdLiterature, dictDetail, literatureDetail, updateLiterature} from "../../../../api";
import {AxiosResponse} from "axios";
import {BASE_UPLOAD_FILE} from "../../../../axios";
import {LiteratureDataType, LiteratureFormType} from "../../../../util/publicType";
import CategoryForm from "../../../../components/CategoryForm";

// 文献更新或者创建表单
const FormLiterature = () => {
    // 路由信息
    const l = useLocation();
    // 判断是否为更新页
    const isUpdate = l.pathname.indexOf("update") >= 0;
    // 详情数据
    const [data, setData] = useState<LiteratureDataType | null>(null)

    // 预览控制
    const [previewOpen, setPreviewOpen] = useState(false);
    // 预览地址
    const [previewImage, setPreviewImage] = useState('');
    // 预览标题
    const [previewTitle, setPreviewTitle] = useState('');
    // 上传图标列表
    const [coverList, setCoverList] = useState<UploadFile[]>([]);
    // 参数获取
    const {id} = useParams();
    // // 分类数据
    // const [category, setCategory] = useState<Array<{ id: string, name: string }>>([]);

    // 上传的附件
    const [fileList, setFileList] = useState<UploadFile[]>([]);

    // 路由
    const n = useNavigate();

    const getDetail = () => {
        literatureDetail(id as string).then(r => {
            const {data} = r.data.data;
            setData(data)
        }, err => message.error(err));
    }

    // 如果是更新页面才执行
    useEffect(() => {
        // 是否为更新页面
        if (isUpdate) {
            getDetail();
        }
    }, [])

    // // data变化时，判断是否拿到数据字典分类id，拿到即执行
    // useEffect(() => {
    //     dictDetail(isUpdate ? data?.dict?.type_id ?? '' : (id as string)).then((r: AxiosResponse) => {
    //         const {data} = r.data.data;
    //         setCategory(data);
    //     }, err => message.error(err))
    // }, [data]);

    // 当分类重新赋值时，即拿到所有数据，因此开始赋值
    useEffect(() => {
        // 判断是否为更新页面
        if (isUpdate) {
            stateForm.setFieldsValue(data);
            const coverList: any = {
                uid: data?.cover?.id,
                status: 'done',
                name: data?.cover?.type,
                url: data?.cover?.path
            };
            const fileList: any = {
                uid: data?.file?.id,
                status: 'done',
                name: data?.file?.type,
                url: data?.file?.path
            }
            setCoverList([coverList]);
            setFileList([fileList]);
        }
    }, [data])

    // 文件i变化
    const handleChange: UploadProps['onChange'] = ({fileList: newFileList}) => {
        setCoverList(newFileList);
    }

    // 上传按钮
    const uploadButton = (
        <div>
            <PlusOutlined/>
            <div style={{marginTop: 8}}>上传</div>
        </div>
    );

    // 表单
    const [stateForm] = Form.useForm();

    // 预览
    const handlePreview = async (file: UploadFile) => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj as RcFile);
        }

        setPreviewImage(file.url || (file.preview as string));
        setPreviewOpen(true);
        setPreviewTitle(file.name || file.url!.substring(file.url!.lastIndexOf('/') + 1));
    };

    // 上传附件
    const props: UploadProps = {
        name: 'file',
        action: BASE_UPLOAD_FILE,
        onChange({fileList: newFileList}) {
            setFileList(newFileList)
        },
    };

    // 完成
    const onFinish = (v: LiteratureFormType) => {
        let request: Promise<AxiosResponse>;
        const file_id = fileList[0]?.response?.data?.data?.id;
        const cover_id = coverList[0]?.response?.data?.data?.id;
        v.file_id = file_id ? file_id : fileList[0]?.uid;
        v.cover_id = cover_id ? cover_id : coverList[0]?.uid;
        if (!v.cover_id) {
            return message.error("请上传封面")
        }
        if (!v.file_id) {
            return message.error("请上传附件")
        }
        if (isUpdate) {
            request = updateLiterature((id as string), v);
        } else {
            request = createdLiterature(v)
        }
        request.then(async () => {
            // 清除数据
            stateForm.resetFields();
            // 清除原本数据
            setFileList([]);
            setCoverList([]);
            if (isUpdate) {
                n(`/literature/${data?.category_id}`);
            }
            await message.success("操作成功");

        }, err => message.error(err));
    };
    // 解決上传附件警告
    const normFile = (e: any) => {
        if (Array.isArray(e)) {
            return e;
        }
        return e && e.fileList;
    };

    return (
        <div style={{padding: "30px 0"}}>
            <div style={{width: "26%", margin: "0 auto"}}>
                <Form
                    form={stateForm}
                    onFinish={onFinish}
                    autoComplete="off"
                >
                    <Form.Item
                        labelCol={{span: 5}}
                        label="文献名字"
                        name="name"
                        rules={[{required: true, message: '请输入名称'}]}
                    >
                        <Input/>
                    </Form.Item>
                    <Form.Item
                        labelCol={{span: 5}}
                        label="文献作者"
                        name="author"
                    >
                        <Input/>
                    </Form.Item>
                    <Form.Item
                        labelCol={{span: 5}}
                        label="文献出版社"
                        name="press"
                    >
                        <Input/>
                    </Form.Item>
                    <Form.Item
                        labelCol={{span: 5}}
                        label="简介"
                        name="introduce"
                    >
                        <TextArea rows={4}/>
                    </Form.Item>
                    <Form.Item
                        labelCol={{span: 5}}
                        label="上传附件"
                        name="file_id"
                        rules={[{required: !(fileList.length >= 1), message: '请上传附件'}]}
                        getValueFromEvent={normFile}
                    >
                        {/*清除数据，保留状态*/}
                        <Upload {...props} accept=".pdf,.mp3,.mp4" fileList={fileList} onRemove={() => setFileList([])}>
                            {
                                fileList.length >= 1 ? null : <Button icon={<UploadOutlined/>}>上传文献附件</Button>
                            }
                        </Upload>
                    </Form.Item>

                    <Form.Item
                        labelCol={{span: 5}}
                        label="上传封面"
                        name="cover_id"
                        rules={[{required: !(coverList.length >= 1), message: '请上传封面'}]}
                    >
                        <Upload
                            accept="image/*"
                            action={BASE_UPLOAD_FILE}
                            listType="picture-card"
                            fileList={coverList}
                            beforeUpload={beforeUpload}
                            onPreview={handlePreview}
                            onChange={handleChange}
                        >
                            {coverList.length >= 1 ? null : uploadButton}
                        </Upload>
                    </Form.Item>

                    <Form.Item
                        labelCol={{span: 5}}
                        label="文献编号"
                        name="code"
                    >
                        <InputNumber min={0}/>
                    </Form.Item>

                    {/*分类组件*/}
                    <CategoryForm id={id as string}
                                  detailData={data}/>

                    <Form.Item wrapperCol={{offset: 10, span: 16}}>
                        <Button type="primary" htmlType="submit" style={{marginRight: "10px"}}>
                            提交
                        </Button>
                        <Button type="primary" htmlType="reset">
                            重置
                        </Button>
                    </Form.Item>
                </Form>
            </div>
            <Modal open={previewOpen} title={previewTitle} footer={null}
                   onCancel={() => setPreviewOpen(false)}>
                <img alt="example" style={{width: '100%'}} src={previewImage}/>
            </Modal>
        </div>
    )
}

export default FormLiterature;